require 'digest/sha1'

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  
  belongs_to  :person,  :class_name => "Person", :foreign_key => :party_id
  
  validates_presence_of :name, :email
  validates_uniqueness_of :name, :email
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  def after_initialize
    @doffer = Role.find_by_code(0)
    @admin  = Role.find_by_code(1)
  end
  
  def before_create
    self.roles.push(Role.find_by_code(0))
  end
  
  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end
  
  def self.authenticate(name,password)
    user = self.find_by_name(name)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  # role methods
  def is_admin
    begin
      self.roles.find(@admin)
    rescue
      result = false
    else
      result = true
    end
    result
  end
  
  def is_doffer
    begin
      self.roles.find(@doffer)
    rescue
      result = false
    else
      result = true
    end
    result
  end
  
  # 'password' is a virtual attribute
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  private
  
  def self.encrypted_password(password, salt)
    string_to_hash  = password + "wibble" + salt # 'wibble' makes it harder to guess
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
end
